package a07_二叉树;

/**
 * <p>
 * a12_平衡二叉树复习3
 * </p>
 *
 * @author flyduck
 * @since 2025/4/9
 */
public class a12_平衡二叉树复习3 {

    //平衡二叉树：左右子树的高度差不超过1
    public boolean isBalanced(TreeNode root) {
        return getHeight(root) != -1;
    }

    //明面上是获取高度，但还有其他含义：返回-1代表不是平衡二叉树
    private int getHeight(TreeNode node){
        if (node == null) {
            return 0;
        }

        int leftHeight = getHeight(node.left);
        int rightHeight = getHeight(node.right);

        if(leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1){
            return -1;
        }

        return Math.max(leftHeight, rightHeight) + 1;
    }
}
